package com.uniflow.controller;

import com.uniflow.common.PageResult;
import com.uniflow.common.Result;
import com.uniflow.entity.TaskCenter;
import com.uniflow.service.TaskCenterService;
import com.uniflow.service.WorkflowService;
import io.swagger.annotations.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
/**
 * 数字驾驶舱控制器
 * 基于Flowable表数据提供统计信息
 */
@RestController
@RequestMapping("/api/v1/dashboard")
@Api(tags = "数据看板")
public class DashboardController {
    
    @Autowired
    private TaskCenterService taskCenterService;
    
    @Autowired
    private WorkflowService workflowService;
    
    /**
     * 获取仪表板统计数据
     * 基于Flowable ACT_RU_TASK、ACT_HI_TASKINST等表计算
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getDashboardStats(@RequestParam(required = false) String userId) {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            // 基于TaskCenter表（关联Flowable表）的统计
            if (userId != null) {
                // 个人统计
                stats.put("pendingTasks", taskCenterService.getPendingTaskCount(userId));
                stats.put("todayNewTasks", taskCenterService.getTodayNewTaskCount(userId));
                stats.put("todayCompletedTasks", taskCenterService.getTodayCompletedTaskCount(userId));
                stats.put("weeklyStats", taskCenterService.getWeeklyTaskStatistics(userId));
                stats.put("monthlyStats", taskCenterService.getMonthlyTaskStatistics(userId));
                stats.put("overdueStats", taskCenterService.getOverdueTaskStatistics(userId));
            } else {
                // 全局统计
                stats.put("totalPendingTasks", taskCenterService.getPendingTaskCount(null));
                stats.put("totalTodayNewTasks", taskCenterService.getTodayNewTaskCount(null));
                stats.put("totalTodayCompletedTasks", taskCenterService.getTodayCompletedTaskCount(null));
                stats.put("globalWeeklyStats", taskCenterService.getWeeklyTaskStatistics(null));
                stats.put("globalMonthlyStats", taskCenterService.getMonthlyTaskStatistics(null));
                stats.put("globalOverdueStats", taskCenterService.getOverdueTaskStatistics(null));
            }
            
            // 任务分类统计
            stats.put("taskCategories", taskCenterService.getTaskCategories());
            stats.put("taskTypes", taskCenterService.getTaskTypes());
            
            // 创建人和执行人统计（Top 10）
            stats.put("topCreators", taskCenterService.getTaskCountByCreator(10));
            stats.put("topAssignees", taskCenterService.getTaskCountByAssignee(10));
            
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("获取仪表板统计数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取最近任务列表
     * 基于TaskCenter表（关联Flowable ACT_RU_TASK表）
     */
    @GetMapping("/recent-tasks")
    public Result<List<TaskCenter>> getRecentTasks(
            @RequestParam(defaultValue = "5") int limit,
            @RequestParam(required = false) String userId) {
        try {
            List<TaskCenter> recentTasks;
            if (userId != null) {
                // 获取用户最近的任务
                recentTasks = taskCenterService.getTasksByAssigneeId(userId, null)
                        .stream()
                        .sorted((t1, t2) -> t2.getCreatedAt().compareTo(t1.getCreatedAt()))
                        .limit(limit)
                        .collect(java.util.stream.Collectors.toList());
            } else {
                // 获取全局最近的任务
                PageResult<TaskCenter> pageResult = taskCenterService.getTaskList(1, limit, null, null, null, null, 
                        null, null, null, null, null, null, null, null, null, null);
                recentTasks = pageResult.getList();
            }
            
            return Result.success(recentTasks);
        } catch (Exception e) {
            return Result.error("获取最近任务列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取任务完成率趋势
     * 基于TaskCenter表的时间统计
     */
    @GetMapping("/completion-trend")
    public Result<List<Map<String, Object>>> getCompletionTrend(
            @RequestParam(required = false) String userId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            LocalDateTime start = startDate != null ? 
                    LocalDateTime.parse(startDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                    LocalDateTime.now().minusDays(30);
            LocalDateTime end = endDate != null ? 
                    LocalDateTime.parse(endDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                    LocalDateTime.now();
            
            List<Map<String, Object>> trend = taskCenterService.getTaskCountByDate(userId, start, end);
            return Result.success(trend);
        } catch (Exception e) {
            return Result.error("获取任务完成率趋势失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取任务平均处理时间
     * 基于TaskCenter表的处理时间统计
     */
    @GetMapping("/average-processing-time")
    public Result<Map<String, Object>> getAverageProcessingTime(
            @RequestParam(required = false) String userId,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            LocalDateTime start = startDate != null ? 
                    LocalDateTime.parse(startDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                    LocalDateTime.now().minusDays(30);
            LocalDateTime end = endDate != null ? 
                    LocalDateTime.parse(endDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                    LocalDateTime.now();
            
            Map<String, Object> avgTime = taskCenterService.getTaskAverageProcessingTime(userId, type, start, end);
            return Result.success(avgTime);
        } catch (Exception e) {
            return Result.error("获取任务平均处理时间失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取过期任务统计
     * 基于TaskCenter表的过期任务分析
     */
    @GetMapping("/overdue-stats")
    public Result<Map<String, Object>> getOverdueStats(@RequestParam(required = false) String userId) {
        try {
            Map<String, Object> overdueStats = taskCenterService.getOverdueTaskStatistics(userId);
            return Result.success(overdueStats);
        } catch (Exception e) {
            return Result.error("获取过期任务统计失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取通知列表（模拟数据，可根据实际需求调整）
     */
    @GetMapping("/notifications")
    public Result<Map<String, Object>> getNotifications(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String userId) {
        try {
            Map<String, Object> result = new HashMap<>();
            List<Map<String, Object>> notifications = new ArrayList<>();
            
            // 基于过期任务生成通知
            if (userId != null) {
                Map<String, Object> overdueStats = taskCenterService.getOverdueTaskStatistics(userId);
                if (overdueStats != null && overdueStats.containsKey("overdueCount")) {
                    int overdueCount = (Integer) overdueStats.get("overdueCount");
                    if (overdueCount > 0) {
                        Map<String, Object> notification = new HashMap<>();
                        notification.put("id", "overdue_" + System.currentTimeMillis());
                        notification.put("title", "过期任务提醒");
                        notification.put("message", "您有 " + overdueCount + " 个任务已过期，请及时处理");
                        notification.put("type", "warning");
                        notification.put("createdTime", LocalDateTime.now());
                        notification.put("read", false);
                        notifications.add(notification);
                    }
                }
                
                // 基于今日新增任务生成通知
                int todayNewTasks = taskCenterService.getTodayNewTaskCount(userId);
                if (todayNewTasks > 0) {
                    Map<String, Object> notification = new HashMap<>();
                    notification.put("id", "new_tasks_" + System.currentTimeMillis());
                    notification.put("title", "新任务通知");
                    notification.put("message", "今日新增 " + todayNewTasks + " 个任务");
                    notification.put("type", "info");
                    notification.put("createdTime", LocalDateTime.now());
                    notification.put("read", false);
                    notifications.add(notification);
                }
            }
            
            result.put("content", notifications);
            result.put("totalElements", notifications.size());
            result.put("totalPages", 1);
            result.put("number", page);
            result.put("size", size);
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取通知列表失败: " + e.getMessage());
        }
    }
}